package com.kly.interceptor;

import com.kly.common.ErrorCode;
import com.kly.common.UserContext;
import com.kly.constant.UserConstant;
import com.kly.exception.BusinessException;
import com.kly.model.domain.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static com.kly.constant.UserConstant.LOGIN_USER_KEY;

/**
 * @author admin
 * @date 2025/2/22
 */
public class LoginInterceptor implements HandlerInterceptor {

    private final RedisTemplate<String, Object> redisTemplate;

    public LoginInterceptor(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断是否登录接口



        String requestURI = request.getRequestURI();
        if (requestURI.contains("/login")) {
            return true;
        }

        if (requestURI.contains("/register")) {
            return true;
        }

        if(request.getMethod().equals("OPTIONS")) {
            return true;
        }


        // 获取请求头中的token
        String token = request.getHeader("token");
        if (token == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }

        // 判断是否登录
        // Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        Object userObj = redisTemplate.opsForValue().get(LOGIN_USER_KEY + token);

        if (userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }

        // 刷新过期时间
        redisTemplate.expire(LOGIN_USER_KEY + token, UserConstant.LOGIN_STATE_EXPIRE_TIME, TimeUnit.MILLISECONDS);

        // 保存用户信息
        User user = (User) userObj;
        UserContext.setUser(user);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
